package com.example.store.service.impl;

import com.example.store.entity.Address;
import com.example.store.mapper.AddressMapper;
import com.example.store.service.IAddressService;
import com.example.store.service.IDistrictService;
import com.example.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/** 新增收货地址的实现类 */
@Service
public class AddressServiceImpl implements IAddressService {
    @Autowired
    private AddressMapper addressMapper;
    // 在添加用户收货地址的业务层依赖于IDistrictService的业务层接口
    @Autowired
    private IDistrictService iDistrictService;

    @Value("${user.address.max-count}")
    private Integer maxCount;

    /**
     * 根据用户id增加收获地址
     *
     * @param uid      用户id
     * @param username 修改人
     * @param address  增加的地址数据
     */
    @Override
    public void addNewAddress(Integer uid, String username, Address address) {
        // 调用收货地址统计的方法
        Integer count = addressMapper.countByUid(uid);
        if(count >= maxCount){
            throw new AddressCountLimitException("用户收货地址超出上限！");
        }

        // 对address对象中的数据补全：省市区
        String provinceName = iDistrictService.getNameByCode(address.getProvinceCode());
        String cityName = iDistrictService.getNameByCode(address.getCityCode());
        String areaName = iDistrictService.getNameByCode(address.getAreaCode());
        address.setProvinceName(provinceName);
        address.setCityName(cityName);
        address.setAreaName(areaName);

        //uid、isDefault、
        address.setUid(uid);
        Integer isDefault = count == 0 ? 1 : 0; // 当收货地址为0，则表示这是第一条地址数据，那么就设置成默认地址
        address.setIsDefault(isDefault);

        //补全4项日志
        address.setCreatedUser(username);
        address.setModifiedUser(username);
        address.setCreatedTime(new Date());
        address.setModifiedTime(new Date());

        //插入收货地址的方法
        Integer rows = addressMapper.insert(address);
        if(rows != 1){
            throw new InsertException("插入用户收货地址时产生未知的异常！");
        }
    }

    /**
     * 根据用户id查询用户地址数据
     *
     * @param uid 用户id
     * @return 用户地址数据
     */
    @Override
    public List<Address> getByUid(Integer uid) {
        List<Address> list = addressMapper.findByUid(uid);
        for (Address address : list) {
//            address.setAid(null);
//            address.setUid(null);
            address.setProvinceCode(null);
            address.setCityCode(null);
            address.setAreaCode(null);
            address.setTel(null);
            address.setIsDefault(null);
            address.setCreatedTime(null);
            address.setCreatedUser(null);
            address.setModifiedUser(null);
            address.setModifiedTime(null);
        }
        return list;
    }

    /**
     * 修该某个用户的某条收货地址数据为默认收货地址
     *
     * @param aid      收货地址id
     * @param uid      用户id
     * @param username 修改者
     */
    @Override
    public void setDefault(Integer aid, Integer uid, String username) {
        Address result = addressMapper.findByAid(aid);
        if(result==null){
            throw new AddressNotFoundException("收货地址不存在");
        }
        // 检测当前获取到的地址数据的归属
        if(!result.getUid().equals(uid)){
            throw new AccessDeniedException("非法数据访问");
        }
        // 先将所有地址数据设置成为非默认
        Integer rows = addressMapper.updateNonDefault(uid);
        if(rows < 1){
            throw new UpdateException("更新数据产生未知的异常");
        }
        // 将用户选中的某条地址数据设置成默认收获地址
        rows = addressMapper.updateDefaultByAid(aid, username, new Date());
        if(rows != 1){
            throw new UpdateException("更新数据产生未知的异常");
        }
    }

    /**
     * 删除用户的收货地址数据
     *
     * @param aid      地址id
     * @param uid      用户id
     * @param username 修改者
     */
    @Override
    public void delete(Integer aid, Integer uid, String username) {
        Address result = addressMapper.findByAid(aid);
        if(result==null){
            throw new AddressNotFoundException("收货地址数据不存在！");
        }
        if(!result.getUid().equals(uid)){
            throw new AccessDeniedException("非法数据访问");
        }

        Integer rows = addressMapper.deleteByAid(aid);
        if(rows != 1){
            throw new DeleteException("删除地址数据时产生未知的异常！");
        }

        Integer count = addressMapper.countByUid(uid);
        if(count == 0){
            //直接终止程序
            return;
        }
        if(result.getIsDefault() == 0){
            return;
        }

        // 将这条数据中的is_default设置为 1
        Address address = addressMapper.findLastModified(uid);
        rows = addressMapper.updateDefaultByAid(address.getAid(), username, new Date());
        if(rows != 1){
            throw new UpdateException("更新数据时产生未知的异常！");
        }

    }

    /**
     * 根据aid来调取地址数据
     *
     * @param aid 地址aid
     * @return 返回值为地址数据
     */
    @Override
    public Address getByAid(Integer aid, Integer uid) {
        Address address = addressMapper.findByAid(aid);
        if(address == null){
            throw new AddressNotFoundException("收货地址数据不存在");
        }
        if(!address.getUid().equals(uid)){
            throw new AccessDeniedException("非法数据访问");
        }
        address.setProvinceCode(null);
        address.setCityCode(null);
        address.setAreaCode(null);
        address.setCreatedTime(null);
        address.setCreatedUser(null);
        address.setModifiedTime(null);
        address.setModifiedUser(null);
        return address;
    }
}
